﻿using System;
using System.Windows.Forms;
using Infragistics.Win.UltraWinGrid;
using POS.BusinessComponents;
using POS.BusinessEntities;

namespace POS.UI.Mantenimientos
{
    public partial class MantProveedoresForm : MantForm
    {
        #region Constructors

        public MantProveedoresForm()
        {
            InitializeComponent();
        }

        #endregion

        #region Declarations
        
        private int selectedId;
        private const string idColumn = "Id";
        private const string nameColumn = "Nombre";

        private readonly BCProveedor bc = new BCProveedor();

        #endregion

        #region Event Handlers

        private void MantProveedoresForm_Load(object sender, EventArgs e)
        {
            LoadList();
            LoadComboBoxes();
            toolStrip.ItemClicked += toolStrip_ItemClicked;

            diasCreditoTextBox.Format = IntegerFormat;
            limiteCreditoTextBox.Format = ShortMoneyFormat;
        }

        private void toolStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Text)
            {
                case NewText:
                    New();
                    break;
            }
        }

        private void grid_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            ConfigureGrid((UltraGrid)sender);
        }

        private void grid_AfterRowActivate(object sender, EventArgs e)
        {
            selectedId = (int)grid.ActiveRow.Cells[idColumn].Value;
            UnPack((BEProveedor)grid.ActiveRow.ListObject);
        }
        
        private void grid_AfterSelectChange(object sender, AfterSelectChangeEventArgs e)
        {
            EnableDisable();
        }

        private void ContactosButton_Click(object sender, EventArgs e)
        {
            new MantContactosForm(TipoContacto.Proveedores, selectedId).ShowDialog();
        }

        private void paisComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            int paisId = 0;
            if (paisComboBox.SelectedValue != null && paisComboBox.SelectedValue is int)
                paisId = (int)paisComboBox.SelectedValue;
            
            provinciaComboBox.ValueMember = "Id";
            provinciaComboBox.DisplayMember = "Nombre";
            provinciaComboBox.DataSource = new BCUbicacion().GetProvinciaList(paisId);
            provinciaComboBox.SelectedIndex = -1;
        }

        #endregion

        #region Methods: Non-Public

        protected new static void ConfigureGrid(UltraGridBase listGrid)
        {
            MantForm.ConfigureGrid(listGrid);
            
            foreach (var col in listGrid.DisplayLayout.Bands[0].Columns)
                col.Hidden = true;

            listGrid.DisplayLayout.Bands[0].Columns[nameColumn].Hidden = false;
        }

        protected override bool ValidateInput()
        {
            var name = nombreTextBox.Text.Trim();

            if (string.IsNullOrEmpty(name))
            {
                ShowError("Debe ingresar el nombre");
                nombreTextBox.Focus();
                return false;
            }
            if (!IsUniqueName(TipoEntidad.Proveedor, name) && selectedId == 0)
            {
                ShowError("El nombre seleccionado ya ha sido ingresado");
                nombreTextBox.Focus();
                return false;
            }
            return true;
        }
        
        private void New()
        {
            ClearControls(Controls);
            nombreTextBox.Focus();
            selectedId = 0;
            ClearGridSelection();
        }

        protected override void Save()
        {
            if (ValidateInput())
            {   
                bc.Save(Pack());
                New();
                LoadList();
            }
        }

        protected override void Delete()
        {
            if (ShowQuestion("¿Está seguro de querer eliminar el proveedor seleccionado?"))
            {
                new BCEntidad(TipoEntidad.Proveedor).Delete(selectedId);
                LoadList();
                ClearControls(Controls);
                ClearGridSelection();
                grid.Select();
            }
        }

        private void LoadComboBoxes()
        {
            tipoComboBox.ValueMember = "Id";
            tipoComboBox.DisplayMember = "Nombre";
            tipoComboBox.DataSource = new BCEntidad(TipoEntidad.TipoProveedor).GetList("");

            paisComboBox.ValueMember = "Id";
            paisComboBox.DisplayMember = "Nombre";
            paisComboBox.DataSource = new BCUbicacion().GetPaisList();

            paisComboBox.SelectedIndex = -1;
            tipoComboBox.SelectedIndex = -1;
        }
        
        private void LoadList()
        {
            grid.DataSource = bc.GetList("");
            ClearGridSelection();
        }

        private void ClearGridSelection()
        {
            grid.Selected.Rows.Clear();
            grid.ActiveRow = null;
            EnableDisable();
        }

        private void EnableDisable()
        {
            toolStrip.Items[DeleteText].Enabled = selectedId > 0;
            contactosButton.Enabled = selectedId > 0;
        }

        private BEProveedor Pack()
        {
            var paisId = 0;
            var provinciaId = 0;
            int diasCredito;
            decimal limiteCredito;

            if (!int.TryParse(diasCreditoTextBox.Text, out diasCredito))
                diasCredito = 0;
            if (!decimal.TryParse(limiteCreditoTextBox.Text, out limiteCredito))
                limiteCredito = 0;
            if (paisComboBox.SelectedIndex > -1)
                paisId = (int)paisComboBox.SelectedValue;
            if (provinciaComboBox.SelectedIndex > -1)
                provinciaId = (int)provinciaComboBox.SelectedValue;

            var entity = new BEProveedor
                {
                     Id = selectedId,
                     Nombre = nombreTextBox.Text.Trim(),
                     Cedula = cedulaTextBox.Text.Trim(),
                     DiasCredito = diasCredito,
                     Direccion = direccionTextBox.Text.Trim(),
                     Email = emailTexBox.Text.Trim(),
                     LimiteCredito = limiteCredito,
                     Notas = notasTextBox.Text.Trim(),
                     PaisId = paisId,
                     ProvinciaId = provinciaId,
                     Telefono = telefonoTextBox.Text.Trim(),
                     TipoId = (int)tipoComboBox.SelectedValue,
                };
            return entity;
        }

        private void UnPack(BEProveedor entity)
        {
            tipoComboBox.SelectedIndex = -1;
            paisComboBox.SelectedIndex = -1;
            provinciaComboBox.SelectedIndex = -1;
           
            nombreTextBox.Text = entity.Nombre;
            cedulaTextBox.Text = entity.Cedula;
            telefonoTextBox.Text = entity.Telefono;
            emailTexBox.Text = entity.Email;
            paisComboBox.SelectedValue = entity.PaisId;
            provinciaComboBox.SelectedValue = entity.ProvinciaId;
            direccionTextBox.Text = entity.Direccion;
            notasTextBox.Text = entity.Notas;
            diasCreditoTextBox.Text = entity.DiasCredito.ToString(IntegerFormat);
            limiteCreditoTextBox.Text = entity.LimiteCredito.ToString(ShortMoneyFormat);
            tipoComboBox.SelectedValue = entity.TipoId;
        }

        #endregion
        
    }
}
